// pages/indexFhm2/indexFhm2.js
var app = getApp()
var ConstantData = require('../../../common/constant_data.js')
var BLELocker = require('../../../common/BLELocker.js')
var commonUtil = require('../../../common/common.js')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    miniImg: {
      use_tip_img_1: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-1.png',
      use_tip_img_2: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-2.png',
      use_tip_img_3: ConstantData.CONSTATNT_DATA.BASE_URL_IMG + '/mini/use-tip-img-3.png',
    },
    phcId: '90777',
    pageName: 'no_back_tip',
    loading_show: false,
    scanTime: 2350,
    showTime: true,
    isSubOffical: true,
    officalSubImg: ConstantData.CONSTATNT_DATA.OFFICAL_SUB_IMG_URL,
    isShowFee: false,
    isShowInfo: false,
    userUseRecord: '',
    costRecord: [],
    noLoginFlg:false
  },

  /**
   * 跳转到关注公众号的页面
   */
  goFollowMp: function () {
    app.goFollowMp(-200006, '关注公众号-未归还使用中')
  },

  contacted() { // mark: 进入客服咨询
    app.contacted()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("no_back_tip---->", options)

    this.setData({
      isSubOffical: app.globalData.isSubOffical,
      orderCode: options.orderCode
    })

    // 记录展示关注公众号日志
    if (!app.globalData.isSubOffical) {
      app.recordShowMpLog(-200006, '关注公众号-未归还使用中')
    }

    getApp().hideLoading();

    let that = this;
    this.getBasicConfigInfo();
    if (app.globalData.returning_tip) {
      that.setData({
        modal: {
          modal_show: true,
          desc: app.globalData.returning_tip,
          cancel: true
        }
      })
    }
    let user_id = wx.getStorageSync('user_id')
    let windowHeight = wx.getStorageSync('systeminfo').windowHeight
    this.setData({
      equId: options.equId,
      equType: options.equType || 'chair',
      hospitalName: options.hospitalName || '',
      user_id: user_id,
      miniVer: ConstantData.CONSTATNT_DATA.MINI_VERSION,
      windowHeight: windowHeight
    })
    let noBackRes = wx.getStorageSync('user_no_back');
    console.log(noBackRes, 'noBackResB')

    if (noBackRes) {
      that.setEquId();

    } else {
      that.getNoback(that.setEquId)
    }
    if (!this.data.hospitalName) {
      this.setData({
        no_eject_show: true
      })
    }
    if (noBackRes && noBackRes.data.noBack && noBackRes.data.noBack.lockType.indexOf('链条') > -1) {
      that.setData({
        isChainLock: '链条'
      })
    } else if (noBackRes && noBackRes.data.noBack && noBackRes.data.noBack.lockType.indexOf('宜家锁') > -1) {
      that.setData({
        isChainLock: '宜家锁'
      })
    } else {
      that.setData({
        isChainLock: '短钩'
      })
    }
    let pages = getCurrentPages()
    let currPage = null //当前页面
    let prevPage = null //上一个页面
    currPage = pages[pages.length - 1] //当前页面
    prevPage = pages[pages.length - 2] //上一个页面
    if (options.pt == 'user_lease') {
      this.setData({
        prevPageName: 'user_lease'
      })
      app.globalData.userStay = false
    } else if (prevPage && (prevPage.data.pageName == 'index' || prevPage.data.pageName == 'no_back_tip')) {
      app.globalData.userStay = true
    } else {
      app.globalData.userStay = false
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    setTimeout(function () {
      getApp().hideLoading()
    }, 2000);
    setTimeout(() => {
      this.setData({
        showTime: false
      })
    }, 4000)
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    getApp().hideLoading();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('no_back_tip-----------onunload', app.globalData.userStay)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  hideModal1: function () {
    this.setData({
      loading_show: false,
      modal: {
        modal_show: false
      },
    })
  },
  /**
   * 扫码归还
   */
  scanBack: function () {
    console.log("scanBack");
    let pages = getCurrentPages()
    let currPage = null //当前页面
    let prevPage = null //上一个页面
    currPage = pages[pages.length - 1] //当前页面
    prevPage = pages[pages.length - 2] //上一个页面
    if (prevPage && prevPage.data.pageName == 'user_deposit') {
      wx.reLaunch({
        url: '../index?pt=noback&depositAutoBack=true',
      })
      return
    }
    wx.reLaunch({
      url: '../index?pt=noback',
    })
  },
  hideEject: function () {
    this.setData({
      no_eject_show: false,
      loading_show: false
    })
  },
  mine_center: function () {
    wx.redirectTo({
      url: '../../user_center/user_center',
    })
  },
  toLocationDetail: function (e) {
    console.log('toLocationDetail-->', e);
    e.currentTarget.dataset.data['hosname'] = e.currentTarget.dataset.hosname
    e.currentTarget.dataset.data['categoryName'] = e.currentTarget.dataset.categoryname
    let locationItem = e.currentTarget.dataset.data;
    wx.navigateTo({
      url: '../../../pkgBak/pages/help/locations/locationDetail/locationDetail?locationDetail=' + JSON.stringify(locationItem)
    })
  },
  getMore: function () {
    wx.navigateTo({
      url: '../../../pkgBak/pages/help/locations/locations?equId=' + this.data.equId
    })
  },
  getLocations() {
    let that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_hospital/info',
        method: 'post',
        header: header,
        data: {
          equId: that.data.equId
        },
        success(res) {
          let locationList = res.data;
          if (!locationList) {
            wx.showToast({
              title: '查找失败',
              icon: 'none'
            })
            return;
          }
          let hospitalName = locationList && locationList.basicInfo ? locationList.basicInfo.hospitalName : ''
          if (locationList.chairList && locationList.chairList.length > 0) { //轮椅
            if (locationList.chairList.length > 2) {
              that.setData({
                getMoreShow: true,
                locations: locationList.chairList,
                hospitalName: hospitalName
              })
            } else {
              that.setData({
                locations: locationList.chairList,
                hospitalName: hospitalName
              })
            }
          } else { //担架
            if (locationList.carList.length > 2) {
              that.setData({
                getMoreShow: true,
                locations: locationList.carList,
                hospitalName: hospitalName
              })
            } else {
              that.setData({
                locations: locationList.carList,
                hospitalName: hospitalName
              })
            }
          }
          if (that.data.locations) {
            that.data.locations.forEach(item => {
              var countsA = item.pileList.filter(item1 => item1.equipCode && item1.equipCode != 0).length;
              item.countsA = countsA;
              item.countsB = item.pileList.length - countsA;
            })
            that.setData({
              locations: that.data.locations,
            })
          }
        }
      })
    })
  },
  /**
   * 获取详情
   */
  getOrderDetail: function () {
    let that = this
    if (app.globalData.loginData && app.globalData.loginData.nophone == 1) {
      //需要重新登录      
      this.setData({
        noLoginFlg: true
      })
      return
    }
    wx.showLoading({
      title: '加载中...',
      mask: true
    });
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + `/lease/recordDetail/${that.data.orderCode}`,
        method: 'get',
        header: header,
        success: function (res) {
          console.log("userRecordsList-->", res);
          if (res.data.result == 0) {
            if (typeof res.data.data.userUseRecord.consumePrice == 'number') {
              res.data.data.userUseRecord.consumePrice = res.data.data.userUseRecord.consumePrice.toString().split('.')
            }
            that.setData({
              costRecord: res.data.data.costRecord,
              userUseRecord: res.data.data.userUseRecord
            })
          } else {
            wx.showToast({
              title: '获取失败'
            })
          }
        },
        complete() {
          getApp().hideLoading()
        }
      })
    })
  },
  /**
   * 获取基本的配置信息
   */
  getBasicConfigInfo() {
    var that = this
    if (app.globalData.isAllowBroadcastBack === 0) {
      that.setData({
        loading_show: false
      })
      return;
    }
    var systemInfo = wx.getStorageSync('systeminfo')
    var phoneType = ''
    if (systemInfo) {
      phoneType = systemInfo.model
    }
    app.executeRequest(function (header) {

      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease/support/base_config',
        method: 'post',
        header: header,
        data: {
          phoneType: phoneType
        },
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            that.setData({
              loading_show: false
            })
            return
          }
          let isJson = commonUtil.isJSON(res.data);
          if (!isJson) {
            commonUtil.recordErrorInfo(ConstantData.err_type.errResJson, "非json:no_back_tip:/lease/support/base_config:" + JSON.stringify(res));
            return;
          }
          var config = JSON.parse(res.data)
          console.log('base_config-->', config);

          // 如果服务器返回了登录页面默认是否勾选同意按钮的配置，则将服务器下发的配置覆盖保存到本地全局配置
          if (config.defCheckAgreeService != undefined) {
            app.globalData.defCheckAgreeService = config.defCheckAgreeService == 1
          }

          if (config.scan_time) {
            let tempArr = config.scan_time.split(',');
            console.log('tempArr-->', tempArr);
            if (tempArr[1]) {
              that.data.scanTime = tempArr[1];
            }
          }

        },
        fail: function (res) {
          commonUtil.recordErrorInfo(41002, "baseconfigFail")
          that.setData({
            loading_show: false
          })
          BLELocker.findDevStopDiscovery('no_back_tip');
        }
      })

    });
  },
  /**
   * 设置陪护床设备id
   */
  setEquId: function () {
    let that = this;
    let noBackRes = wx.getStorageSync('user_no_back');
    console.log(noBackRes, 'noBackResA')
    if (noBackRes && noBackRes.data.noBack.hid && (that.data.equId == that.data.phcId || that.data.equId == noBackRes.data.noBack.hid)) {
      //如果是共享陪护床
      that.setData({
        pileId: noBackRes.data.noBack.hid,
        equId: noBackRes.data.noBack.equId
      })
    } else {
      that.getLocations();
      that.getOrderDetail()
    }
    if (noBackRes && noBackRes.data.noBack && noBackRes.data.noBack.lockType.indexOf('链条') > -1) {
      that.setData({
        isChainLock: '链条'
      })
    } else if (noBackRes && noBackRes.data.noBack && noBackRes.data.noBack.lockType.indexOf('宜家锁') > -1) {
      that.setData({
        isChainLock: '宜家锁'
      })
    } else {
      that.setData({
        isChainLock: '短钩'
      })
    }
  },
  /**
   * 查询未归还信息
   */
  getNoback: function (callback) {
    let that = this;
    app.executeRequest(function (header) {
      wx.request({
        url: ConstantData.CONSTATNT_DATA.BASE_URL + '/lease_user/is_con', //判断是否有未归还
        header: header,
        success: function (res) {
          let netErr = app.handleRes(res, that);
          if (netErr) {
            return
          }

          if (res.data.noBack) {
            wx.setStorageSync("user_no_back", res);
          }
          that.setEquId();
        },
        fail: function (res) {
          app.handleRes(res, that);
        }
      })
    })
  },
  //查看收费规则
  toFeeRule() {
    wx.navigateTo({
      url: '/pkgNew/pages/feeRule/index?selectOrder=' + `${this.data.userUseRecord?encodeURIComponent(JSON.stringify(this.data.userUseRecord)):''}` + `&noLoginFlg=${this.data.noLoginFlg}`,
    })
  },
  //打开租借费用
  openCosts: function () {
    this.setData({
      isShowFee: !this.data.isShowFee,
    })
  },
  //打开租借信息
  openInfo: function () {
    this.setData({
      isShowInfo: !this.data.isShowInfo,
    })
  },
  /**
   * 客服中心
   */
  toService: function () {
    wx.switchTab({
      url: '/pages/servicer/index'
    })
  },
  /**
   * 故障上报
   */
  tofault: function () {
    wx.navigateTo({
      url: '/pkgNew/pages/faultReporting/index',
    })
  }
})